package com.csu.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csu.mall.common.utils.PageUtils;
import com.csu.mall.common.utils.Query;
import com.csu.mall.product.dao.CategoryBrandRelationDao;
import com.csu.mall.product.dao.CategoryDao;
import com.csu.mall.product.entity.CategoryEntity;
import com.csu.mall.product.service.CategoryService;
import com.csu.mall.product.vo.Catelog2Vo;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private Gson gson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 返回三级分类菜单
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //按catLevel正序拿到所有菜单种类，保证父节点先入map
        List<CategoryEntity> categoryEntityList = categoryDao.selectCategory();
        Map<Long, CategoryEntity> map = new HashMap<>();
        List<CategoryEntity> resList = new ArrayList<>();
        for(CategoryEntity category : categoryEntityList){
            map.put(category.getCatId(), category);
            if(category.getCatLevel() == 1){
                resList.add(category);
            }else {
                CategoryEntity parentCategory = map.get(category.getParentCid());
                //如果父节点为空，跳过；但是一般情况下，父节点不会为空
                if(parentCategory == null) continue;
                if(parentCategory.getChildren() == null){
                    parentCategory.setChildren(new ArrayList<>());
                }
                parentCategory.getChildren().add(category);
            }
        }
        return resList;
    }

    /**
     * 获取分类的层级路径
     * @param catelogId
     * @return
     */
    @Override
    public Long[] getCatelogPath(Long catelogId) {
        Long curId = catelogId;
        List<Long> rs = new ArrayList<>();
        while (curId != 0){
            rs.add(curId);
            Long parentCid = categoryDao.getParentCid(curId);
            curId = parentCid;
        }

        Long[] rsArr = null;
        if(rs.size() > 0){
            rsArr = new Long[rs.size()];
            int len = rs.size();
            for(int i=0;i<len;i++){
                rsArr[i] = rs.get(rs.size() - i - 1);
            }
        }
        return rsArr;
    }

    //key中是spEL表达式，getLevel1Categories得加单引号
    @Caching(
            evict = {@CacheEvict(value = {"category", "product"}, key = "'getLevel1Categories'")}
    )
    @Override
    public void updateEntity(CategoryEntity category) {
        this.updateById(category);
        if(!StringUtils.isEmpty(category.getName())){
            categoryBrandRelationDao.batchUpdateCategoryName(category.getCatId(), category.getName());
        }
    }

    // @Cacheable, 读模式下，如果缓存中有数据，不执行以下方法，直接从缓存拿数据，不用去访问DB；
    // 并且将db中的数据更新到缓存
    //value, 指定数据放到名字为"category","product"的缓存分区中，分区命名参考了业务场景
    // key中的是spEL表达式，指定category以及product分区下某个key的名称为方法名
    //不过加了key之后，value中指定的缓存分区不会显示在key的名字上了，可能只是作为逻辑分区，名字隐藏起来了。
    @Cacheable(value = {"category", "product"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        System.out.println("访问数据库了。。。");
        return categoryDao.getLevelCategories(1);
    }
    //TODO

    @Override
    @Cacheable(value = {"category", "product"}, key = "#root.method.name")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        String catalogEntities = stringRedisTemplate.opsForValue().get("catalogEntities");
        if(catalogEntities == null){
           Map<String, List<Catelog2Vo>> listMap = getCatalogJsonFromDb();
            stringRedisTemplate.opsForValue().set("catalogEntities", gson.toJson(listMap));
           return listMap;
        }

        //借助TypeToken 将catalogEntities 解析成 Map<String, List<Catelog2Vo>> 形式
        return gson.fromJson(catalogEntities, new TypeToken<Map<String, List<Catelog2Vo>>>(){}.getType());
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2、封装上面面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }


            return catelog2Vos;
        }));
        return parent_cid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        return collect;
    }
}